import 'dart:convert';
import 'dart:io';

import 'package:star_author/utils/common_util/file_util.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_keys_constant.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_util.dart';
import 'package:star_author/utils/http/http_util.dart';

// Map _map = {"image": "https://ibb.co/swPpnJk", "page": "/","is_open":true};
class SplashAdUtil {
  ///  获取开屏广告图片本地信息实体，此实体的id用于判断是否与服务器的广告id一致，来实现开屏广告图片下载
  static Future<Map?> getAdImageLocalInfo() async {
    String infoStr =
        SpUtil.getString(SpKeysConstant.AD_IMAGE_LOCAL_INFO, defValue: '')!;

    LogUtil.v('getAdImageLocalInfo $infoStr');

    if (infoStr.isEmpty) {
      return null;
    } else {
      return json.decode(infoStr);
    }
  }

  ///  设置开屏广告图片本地信息实体
  static setAdImageLocalInfo(Map adImageInfo) {
    String infoStr = json.encode(adImageInfo);
    SpUtil.putString(SpKeysConstant.AD_IMAGE_LOCAL_INFO, infoStr);
  }

  static Future<String> getAdImagePath(Map adImageInfo) async {
    String imgFileName = "";

    String splash_ad_image_url = adImageInfo['image'] ??
        ""; // 兼容旧版本，旧版本存储的是 support directory 的全路径，每次重启都会变化
    if (splash_ad_image_url.isNotEmpty) {
      imgFileName = splash_ad_image_url
          .substring(splash_ad_image_url.lastIndexOf('/') + 1);
    }

    return (await FileUtil.getInternalPathOfDirectory(
            FileUtil.DirectoryImage)) +
        '/$imgFileName';
  }

  static Future<void> checkIfShouldDownloadAdImage(Map remoteInfo) async {
    Map? localInfo = await getAdImageLocalInfo();
    LogUtil.v("object${remoteInfo['is_open']}");

    if (remoteInfo['is_open'] ?? false) {
      // 文件发生变化则更改图片，并修改本地缓存数据
      if (localInfo == null || localInfo['image'] != remoteInfo['image']) {
        String suffix =
            remoteInfo['image'].substring(remoteInfo['image'].lastIndexOf('.'));

        remoteInfo['image'] = 'adImage' + suffix;

        String adImagePath = await getAdImagePath(remoteInfo);

        downloadAdImage(remoteInfo, adImagePath);
      } else {
        // 判断本地广告图片是否下载成功，否则重新下载
        String localImagePath = await getAdImagePath(localInfo);
        File file = File(localImagePath);

        if (!file.existsSync()) {
          downloadAdImage(localInfo, localImagePath);
        }
      }
    } else {
      // 广告关闭后删除本地缓存的图片
      if (localInfo != null) {
        String localImagePath = await getAdImagePath(localInfo);

        var file = File(localImagePath);
        if (await file.exists()) {
          await file.delete();

          LogUtil.v('广告图片已删除！');

          remoteInfo['image'] = '';
          setAdImageLocalInfo(remoteInfo);
        }
      }
    }
  }

  static Future<void> downloadAdImage(
      Map adImageInfo, String adImagePath) async {
    HttpUtil.downloadFile(adImageInfo['image'], adImagePath, {},
        progressCallback: (current, total) {
      LogUtil.v("当前下载广告图片进度为：${((current / total) * 100).toInt()}%");
    }).then((value) {
      if (value.statusCode == 200) {
        SplashAdUtil.setAdImageLocalInfo(adImageInfo);
      }
    }).catchError((e) {
      LogUtil.v('download splash ad image error: $e');
      return null;
    });
  }
}
